package com.linlang.grasharepro.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.linlang.grasharepro.R;
import com.linlang.grasharepro.activity.ADBanner.BaseWebActivity;
import com.linlang.grasharepro.adapter.ImagePagerAdapter;
import com.linlang.grasharepro.common.ViewFlow;
import com.linlang.grasharepro.dao.UserDB;
import com.linlang.grasharepro.model.User;
import com.linlang.grasharepro.view.CircleFlowIndicator;
import com.linlang.grasharepro.view.MyGridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lixin on 2016-8-8.
 */
public class ScoreActivity extends Activity {

    private ViewFlow mViewFlow;
    private CircleFlowIndicator mFlowIndicator;
    private ArrayList<String> imageUrlList = new ArrayList<String>();
    ArrayList<String> linkUrlArray = new ArrayList<String>();
    ArrayList<String> titleList = new ArrayList<String>();
    private int mCurrPos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);
        initView();
        initBanner(imageUrlList);
        initRollNotice();
    }

    public void back(View view) {
        finish();
    }

    private void initView() {
        MyGridView grid_able = (MyGridView) this.findViewById(R.id.grid_score_able);
        MyGridView grid_enable = (MyGridView) this.findViewById(R.id.grid_score_enable);
        ArrayList<HashMap<String, Object>> ablegrid = new ArrayList<HashMap<String, Object>>();
        ArrayList<HashMap<String, Object>> enablegrid = new ArrayList<HashMap<String, Object>>();

        View convertView = View.inflate(this, R.layout.item_grid, null);
        Button ablebutton = (Button) convertView.findViewById(R.id.item_grid_button);
        Button enablebutton = (Button) convertView.findViewById(R.id.item_grid_button);
        ablebutton.setVisibility(View.VISIBLE);

        for (int i = 1; i < 10; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();// 建立hashmap对象
            HashMap<String, Object> mapx = new HashMap<String, Object>();// 建立hashmap对象
            switch (i) {
                case 1:
                    map.put("ItemImage", R.drawable.duihuan1);
                    mapx.put("ItemImage", R.drawable.duihuan10);
                    map.put("ItemText", "4360");
                    mapx.put("button", ablebutton);
                    mapx.put("ItemText", "2000");
                    ablegrid.add(mapx);
                    enablegrid.add(map);
                    continue;
                case 2:
                    map.put("ItemImage", R.drawable.duihuan2);
                    mapx.put("ItemImage", R.drawable.duihuan11);
                    mapx.put("ItemText", "1500");
                    map.put("ItemText", "4530");
                    mapx.put("button", ablebutton);
                    ablegrid.add(mapx);
                    enablegrid.add(map);
                    continue;
                case 3:
                    map.put("ItemImage", R.drawable.duihuan3);
                    mapx.put("ItemImage", R.drawable.duihuan12);
                    mapx.put("ItemText", "1200");
                    map.put("ItemText", "5600");
                    mapx.put("button", ablebutton);
                    ablegrid.add(mapx);
                    enablegrid.add(map);
                    continue;
                case 4:
                    map.put("ItemImage", R.drawable.duihuan4);
                    map.put("ItemText", "3490");
                    mapx.put("button", ablebutton);
                    enablegrid.add(map);
                    continue;
                case 5:
                    map.put("ItemImage", R.drawable.duihuan5);
                    map.put("ItemText", "4000");
                    mapx.put("button", ablebutton);
                    enablegrid.add(map);
                    continue;
                case 6:
                    map.put("ItemImage", R.drawable.duihuan6);
                    map.put("ItemText", "2300");
                    mapx.put("button", ablebutton);
                    enablegrid.add(map);
                    continue;
                case 7:
                    map.put("ItemImage", R.drawable.duihuan7);
                    map.put("ItemText", "3400");
                    mapx.put("button", ablebutton);
                    enablegrid.add(map);
                    continue;
                case 8:
                    map.put("ItemImage", R.drawable.duihuan8);
                    map.put("ItemText", "4500");
                    mapx.put("button", ablebutton);
                    enablegrid.add(map);
                    continue;
                case 9:
                    map.put("ItemImage", R.drawable.duihuan9);
                    map.put("ItemText", "5000");
                    mapx.put("button", ablebutton);
                    enablegrid.add(map);
                    continue;
            }
        }
//        SimpleAdapter ablegridItems = new SimpleAdapter(this, ablegrid,
//                R.layout.item_grid, new String[]{"ItemImage", "ItemText", "button"},
//                new int[]{R.id.item_grid_image, R.id.item_grid_text, R.id.item_grid_button});
//        SimpleAdapter enablegridItems = new SimpleAdapter(this, enablegrid,
//                R.layout.item_grid, new String[]{"ItemImage", "ItemText", "button"},
//                new int[]{R.id.item_grid_image, R.id.item_grid_text, R.id.item_grid_button});

        ScoreAdapter ablegridItems = new ScoreAdapter(this, ablegrid,
                R.layout.item_grid, new String[]{"ItemImage", "ItemText", "button"},
                new int[]{R.id.item_grid_image, R.id.item_grid_text, R.id.item_grid_button});
        ScoreAdapter enablegridItems = new ScoreAdapter(this, enablegrid,
                R.layout.item_grid, new String[]{"ItemImage", "ItemText", "button"},
                new int[]{R.id.item_grid_image, R.id.item_grid_text, R.id.item_grid_button});

        grid_able.setAdapter(ablegridItems);// 添加适配器
        grid_enable.setAdapter(enablegridItems);// 添加适配器

//        grid_able.setOnItemClickListener(new ItemClickListener());
//        grid_enable.setOnItemClickListener(new ItemClickListener());

        mViewFlow = (ViewFlow) this.findViewById(R.id.viewflow);
        mFlowIndicator = (CircleFlowIndicator) this.findViewById(R.id.viewflowindic);
        imageUrlList.clear();
        linkUrlArray.clear();
        titleList.clear();
        imageUrlList.add(R.drawable.baidu + "");
        imageUrlList.add(R.drawable.sina + "");
        imageUrlList.add(R.drawable.taobao + "");

        linkUrlArray
                .add("https://www.baidu.com");
        linkUrlArray
                .add("http://www.sina.com");
        linkUrlArray
                .add("http://www.taobao.com");
        titleList.add("百度搜索引擎");
        titleList.add("新浪新闻与微博");
        titleList.add("淘宝网，淘啊淘 ");
    }

    private void initRollNotice() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        moveNext();
                    }
                });

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 0, 4000);
    }

    private void moveNext() {
        setView(this.mCurrPos, this.mCurrPos + 1);
    }

    private void setView(int curr, int next) {
        View noticeView = getLayoutInflater().inflate(R.layout.notice_item,
                null);
        TextView notice_tv = (TextView) noticeView.findViewById(R.id.notice_tv);
        if ((curr < next) && (next > (titleList.size() - 1))) {
            next = 0;
        } else if ((curr > next) && (next < 0)) {
            next = titleList.size() - 1;
        }
        notice_tv.setText(titleList.get(next));
        notice_tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bundle = new Bundle();
                bundle.putString("url", linkUrlArray.get(mCurrPos));
                bundle.putString("title", titleList.get(mCurrPos));
                Intent intent = new Intent(ScoreActivity.this,
                        BaseWebActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        mCurrPos = next;

    }

    private void initBanner(ArrayList<String> imageUrlList) {

        mViewFlow.setAdapter(new ImagePagerAdapter(ScoreActivity.this, imageUrlList,
                linkUrlArray, titleList).setInfiniteLoop(true));
        mViewFlow.setmSideBuffer(imageUrlList.size()); // 实际图片张数，
        // 我的ImageAdapter实际图片张数为3

        mViewFlow.setFlowIndicator(mFlowIndicator);
        mViewFlow.setTimeSpan(4000);
        mViewFlow.setSelection(imageUrlList.size() * 1000); // 设置初始位置
        mViewFlow.startAutoFlowTimer(); // 启动自动播放
    }

    /**
     * GridView 点击事件
     */
//    class ItemClickListener implements AdapterView.OnItemClickListener {
//        @Override
//        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
//            String ny = (String) item.get("ItemText");
//            item.get("button");
//            showPopupWindow(view);
//        }
//    }

    private void showPopupWindow(View view) {
        View parentView = LayoutInflater.from(this).inflate(
                R.layout.activity_score, null);

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.score_info, null);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        EditText tv_mail = (EditText) contentView.findViewById(R.id.tv_mymail);
        EditText tv_contactWay = (EditText) contentView.findViewById(R.id.tv_mycontactWay);
        EditText tv_location = (EditText) contentView.findViewById(R.id.tv_mylocation);

        //获取用户登陆信息
        SharedPreferences preferences = getSharedPreferences("userInfo",
                Activity.MODE_PRIVATE);
        String account = preferences.getString("account", "");

        UserDB userDB = new UserDB(this);
        userDB.open();
        User user = userDB.getUser(account);

        tv_mail.setText(user.getMail());
        tv_contactWay.setText(user.getContactWay());
        tv_location.setText(user.getLocation());

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.list_background_imgbg));

        // 设置好参数之后再show
        popupWindow.setWidth(800);
        popupWindow.showAtLocation(parentView, Gravity.CENTER, 60, 0);
    }

    class ScoreAdapter extends SimpleAdapter {
        private Context context;
        private List<? extends Map<String, ?>> data;
        private int resource;
        private String[] from;
        private int[] to;

        public ScoreAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            this.context = context;
            this.data = data;
            this.resource = resource;
            this.from = from;
            this.to = to;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(ScoreActivity.this, R.layout.item_grid, null);
            }

            Button ablebutton = (Button) convertView.findViewById(R.id.item_grid_button);
            ImageView item_grid_image = (ImageView) convertView.findViewById(R.id.item_grid_image);
            TextView item_grid_text = (TextView) convertView.findViewById(R.id.item_grid_text);

            HashMap<String, Object> data = (HashMap<String, Object>) super.getItem(position);
            int imageResource = (int) data.get("ItemImage");
            String itemText = data.get("ItemText").toString();
            item_grid_image.setImageResource(imageResource);
            item_grid_text.setText(itemText);
            if (Integer.valueOf(itemText).doubleValue() <= 2000) {
                ablebutton.setVisibility(View.VISIBLE);
                ablebutton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPopupWindow(v);
                    }
                });
            }

            return convertView;


        }
    }
}